// File: src/core/auth/AuthManager.cpp
#include "AuthManager.h"
#include <fstream>
#include <iostream>
#include <sstream>

bool AuthManager::userExists(const std::string& username){
    if (userDB.find(username) != userDB.end())
        return true;
    return false;
}

bool AuthManager::registerUser(const std::string& username, const std::string& password) {
    if (userDB.find(username) != userDB.end()) {
        std::cerr << "用户已存在: " << username << std::endl;
        return false;
    }
    
    userDB[username] = hashPassword(password);
    saveToFile();
    std::cout << "用户注册成功: " << username << std::endl;
    return true;
}

bool AuthManager::authenticate(const std::string& username, const std::string& password) {
    auto it = userDB.find(username);
    if (it == userDB.end()) {
        std::cerr << "用户不存在: " << username << std::endl;
        return false;
    }
    
    if (it->second == hashPassword(password)) {
        std::cout << "认证成功: " << username << std::endl;
        return true;
    }
    
    std::cerr << "密码错误: " << username << std::endl;
    return false;
}

void AuthManager::saveToFile() {
    std::ofstream file("users.tmdb");
    if (!file) {
        std::cerr << "无法打开用户数据文件" << std::endl;
        return;
    }
    
    for (const auto& [user, hash] : userDB) {
        file << user << ":" << hash << "\n";
    }
}

void AuthManager::loadFromFile() {
    std::ifstream file("users.tmdb");
    if (!file) return;
    
    std::string line;
    while (std::getline(file, line)) {
        size_t pos = line.find(':');
        if (pos != std::string::npos) {
            std::string user = line.substr(0, pos);
            std::string hash = line.substr(pos + 1);
            userDB[user] = hash;
        }
    }
}
